package com.forum.model.dao;

import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.Topic;
import com.forum.model.util.SessionManager;

public class TopicDAO implements GenericDAO<Topic, Long> {

	private Session session;

	@Override
	public boolean insert(Topic topic) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(topic);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(Topic topic) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(topic);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(Topic topic) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(topic);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public Topic getObjectById(Long id) {
		Topic topic = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			topic = (Topic) session.get(Topic.class, id);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return topic;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Topic> getAll() {
		List<Topic> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<Topic>) session.createQuery("from Topic").list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}

	@SuppressWarnings("unchecked")
	public List<Topic> getAll(String sectionName) {
		List<Topic> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<Topic>) session.createQuery(
					"from Topic where sectionName = '" + sectionName + "'").list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}